//
//  IGContentTabelViewCell.m
//  ImGuider
//
//  Created by 王鹏宇 on 2017/8/23.
//  Copyright © 2017年 AudioCtrip. All rights reserved.
//

#import "IGContentTabelViewCell.h"
#import "GuiderVideosViewController.h"
#import "IGPageViewController.h"
#define  ContentCellH   108

@interface IGContentTabelViewCell()<UIScrollViewDelegate,UIPageViewControllerDelegate,UIPageViewControllerDataSource>

@property (nonatomic, strong)UIScrollView *pageScrollView;

@property (nonatomic, strong)IGPageViewController * pageVC;

@property (nonatomic)NSInteger currentPage;

@property (nonatomic, strong) NSMutableArray<UIViewController *> * dataArray;


@end
@implementation IGContentTabelViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
}

- (void)dealloc {
    //清除监听
    [self.pageScrollView removeObserver:self forKeyPath:@"panGestureRecognizer.state"];
    
}


- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}



//- (UIScrollView *)pageScrollView {
//    
//    if (!_pageScrollView) {
//        
//        _pageScrollView = [[UIScrollView alloc] init];
//        
//        [self.contentView addSubview:_pageScrollView];
//        [_pageScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
//        
//            _pageScrollView.delegate = self;
//            _pageScrollView.pagingEnabled = YES;
//            make.edges.equalTo(self.contentView);
//        }];
//    }
//    
//    return _pageScrollView;
//}


- (void)configData:(NSArray<UIViewController *> *)controllers {
    
//    self.dataArray = [NSMutableArray arrayWithArray:controllers];
//    
//    for (int i= 0; i < controllers.count; i ++) {
//        
//        UIViewController * vc = controllers[i];
//        
//        vc.view.frame = CGRectMake(SCREEN_WIDTH * i, 0, SCREEN_WIDTH, SCREEN_HEIGHT - ContentCellH);
//        
//        [self.pageScrollView addSubview:vc.view];
//    }
//   
//    self.pageScrollView.contentSize = CGSizeMake(SCREEN_WIDTH * controllers.count, 0);
    
    NSDictionary *option = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:UIPageViewControllerSpineLocationMin] forKey:UIPageViewControllerOptionSpineLocationKey];
    self.pageVC = [[IGPageViewController alloc]
                   initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll
                   navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
                   options:option];
    
    self.pageVC.dataSource = self;
    self.pageVC.delegate = self;
    
    
    
    self.dataArray = [NSMutableArray arrayWithArray:controllers];
    
    [self.pageVC setViewControllers:@[self.dataArray[0]] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
    self.pageVC.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.contentView addSubview:self.pageVC.view];
    
//    for (UIView *view in self.pageVC.view.subviews) {
//        if ([view isKindOfClass:[UIScrollView class]]) {
//            //监听拖动手势
//            self.pageScrollView = (UIScrollView *)view;
//            [self.pageScrollView addObserver:self
//                                  forKeyPath:@"panGestureRecognizer.state"
//                                     options:NSKeyValueObservingOptionNew
//                                     context:nil];
//        }
//    }
    [self.pageVC.view mas_makeConstraints:^(MASConstraintMaker* make) {
        make.edges.equalTo(self.contentView);
    }];
}

- (void)setSelectedIndex:(NSInteger)selectedIndex {
    
   [self.pageVC setViewControllers:@[self.dataArray[selectedIndex]] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    if ([otherGestureRecognizer.view isKindOfClass:[UITableView class]]) {
        return YES;
    }
    return NO;
}


- (void)setCanScroll:(BOOL)canScroll {
    
    _canScroll = canScroll;
    
    //修改所有的子控制器的状态
    
    for ( BaseViewController *vc in self.dataArray) {
        
        vc.canScroll = canScroll;
        
        if (!canScroll) {
            vc.subScrollView.contentOffset = CGPointZero;
        }
    }
}

#pragma mark  -- 观察者模式

//监听拖拽手势的回调
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSKeyValueChangeKey,id> *)change
                       context:(void *)context {
    if (((UIScrollView *)object).panGestureRecognizer.state == UIGestureRecognizerStateChanged) {
        IGLog(@"bottomSView 滑动了");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PageViewGestureState" object:@"changed"];
    } else if (((UIScrollView *)object).panGestureRecognizer.state == UIGestureRecognizerStateEnded) {
        IGLog(@"结束拖拽");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PageViewGestureState" object:@"ended"];
    }
}

- (void)pageViewScrollToPositon:(NSString *)str {
    
    if (_delegate && [_delegate respondsToSelector:@selector(scrollToBottomWithPosition:)]) {
        [_delegate scrollToBottomWithPosition:str];
    }
}

#pragma mark - UIPageViewControllerDataSource


/**
 *  @brief 点击或滑动 UIPageViewController 左侧边缘时触发
 *
 *  @param pageViewController 翻页控制器
 *  @param viewController     当前控制器
 *
 *  @return 返回前一个视图控制器
 */
- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController
               viewControllerBeforeViewController:(UIViewController *)viewController {
    // 计算当前 viewController 数据在数组中的下标
    NSUInteger index = [self.dataArray indexOfObject:viewController];
    
    // index 为 0 表示已经翻到最前页
    if (index == 0 ||index == NSNotFound) {
        return  nil;
    }
    
    // 下标自减
    index --;
    
    return self.dataArray[index];
}


/**
 *  @brief 点击或滑动 UIPageViewController 右侧边缘时触发
 *
 *  @param pageViewController 翻页控制器
 *  @param viewController     当前控制器
 *
 *  @return 返回下一个视图控制器
 */
- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController
                viewControllerAfterViewController:(UIViewController *)viewController {
    // 计算当前 viewController 数据在数组中的下标
    NSUInteger index = [self.dataArray indexOfObject:viewController];
    // index为数组最末表示已经翻至最后页
    if (index == NSNotFound ||
        index == (self.dataArray.count - 1)) {
        return nil;
    }
    
    // 下标自增
    index ++;
    return self.dataArray[index];
}


/**
 *  @brief 转场动画即将开始
 *
 *  @param pageViewController     翻页控制器
 *  @param pendingViewControllers 即将展示的控制器
 */
- (void)pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers {
    
}

/**
 *  @brief 该方法会在 UIPageViewController 翻页效果出发之后，尚未完成时执行
 *
 *  @param pageViewController      翻页控制器
 *  @param finished                动画完成
 *  @param previousViewControllers 前一个控制器(非当前)
 *  @param completed               转场动画执行完
 */
- (void)pageViewController:(UIPageViewController *)pageViewController
        didFinishAnimating:(BOOL)finished
   previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers
       transitionCompleted:(BOOL)completed {
    
    NSUInteger index = [self.dataArray indexOfObject:self.pageVC.viewControllers.firstObject];
    if (_delegate && [_delegate respondsToSelector:@selector(pageChangeToNum:)]) {
        [_delegate pageChangeToNum:index];
    }
}
@end
